package lion.framework.core.web.path;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import lion.dev.lang.InterceptorAdaptor;
import lion.dev.lang.MapJ;
import lion.framework.core.db.DB;
import lion.framework.core.db.SessionFactory;
import lion.framework.core.web.anno.ExecuteInterceptor;

/**
 * 请求方法拦截，该拦截器对请求进行事务拦截，如果发生异常，则该请求中的事务全部回滚
 * 
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年3月18日
 */
@ExecuteInterceptor(false)
public class TransactionInterceptor extends InterceptorAdaptor {

	private Log log = LogFactory.getLog(TransactionInterceptor.class);
	private boolean haveException = false;

	/**
	 * 在请求方法执行完成后，对数据库事务进行处理，有异常则全部回滚，无异常则全部提交 多支持对多数据库的事务处理
	 */
	@Override
	public void onPost(Object... args) throws Exception {

		MapJ currentDBs = SessionFactory.getCurrentDBMap();
		if (currentDBs == null || currentDBs.isEmpty()) { return; }

		for (String key : currentDBs.keySet()) {
			DB db = currentDBs.getE(key);
			try {
				while (db.haveUncommitedTrans()) {
					if (haveException) {
						db.rollback();
					} else {
						db.commit();
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}

	/**
	 * 当发生异常时，设立异常标识
	 */
	@Override
	public void onException(Object... args) throws Exception {

		haveException = true;
		throw (Exception) args[2];
	}

}
